#include "I2CDevice.hpp"
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/i2c-dev.h>
#include <stdexcept>
#include <cstring>

I2CDevice::I2CDevice(const std::string& devicePath, uint8_t address) : addr(address) {
    fd = open(devicePath.c_str(), O_RDWR);
    if (fd < 0) {
        throw std::runtime_error("Failed to open I2C device");
    }

    if (ioctl(fd, I2C_SLAVE, addr) < 0) {
        throw std::runtime_error("Failed to set I2C address");
    }
}

I2CDevice::~I2CDevice() {
    close();
}

void I2CDevice::close() {
    if (fd >= 0) {
        ::close(fd);
        fd = -1; // Invalidate the file descriptor
    }
}

bool I2CDevice::writeByte(uint8_t reg, uint8_t data) {
    uint8_t buf[2] = {reg, data};
    return write(fd, buf, 2) == 2;
}

bool I2CDevice::readBytes(uint8_t reg, uint8_t* buffer, size_t length) {
    if (write(fd, &reg, 1) != 1) return false;
    return read(fd, buffer, length) == (ssize_t)length;
}
